import { defineStore } from 'pinia'
import { accountLoginRequest, getUserInfoById, getUserMenuByRoleId } from '@/service/login'
import type { Iaccount } from '@/types'
import { localCache } from '@/utils/storage'
import router from '@/router'
import { LOGIN_TOKEN } from '@/global/constans'

//userInfo返回数据太多，直接返回any类型
interface ILoginState {
  token: string
  userInfo: any
  userMenus: any
}

//指定一个函数返回类型
//普通函数
// function foo(): number {
//   return 123
// }

//箭头函数函数返回类型
// const bar = (): string => {
//   return '12111'
// }

const useLoginStore = defineStore('login', {
  //指定state的类型
  state: (): ILoginState => ({
    token: localCache.getStorage(LOGIN_TOKEN) ?? '',
    userInfo: localCache.getStorage('userInfo') ?? {},
    userMenus: localCache.getStorage('userMenuList') ?? []
  }),

  actions: {
    async loginAccountAction(account: Iaccount) {
      // 1.向服务器发送网络请求(携带账号和密码)
      const res = await accountLoginRequest(account)
      const id = res.data.id
      const name = res.data.name
      this.token = res.data.token
      //本地缓存
      localCache.setStorage(LOGIN_TOKEN, this.token)

      //在登录后获取用户的详细信息(mock模拟数据，每次都是这个数据，除非改useMock)
      const userInfo = await getUserInfoById(id)
      //保存用户信息到缓存
      this.userInfo = userInfo
      localCache.setStorage('userInfo', userInfo)

      //根据用户的信息获取角色权限(存入缓存)
      const userMenuResult = await getUserMenuByRoleId(id)
      this.userMenus = userMenuResult.data
      localCache.setStorage('userMenuList', userMenuResult.data)

      //跳转main页面
      router.push('/main')
    }
  }
})

export default useLoginStore
